<template>
  <a-card>
    <div>
      <a-form layout="horizontal">
        <div>
          <a-row >
            <a-col :md="6" :sm="24" >
              <a-form-item label="选择园区" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                <a-select placeholder="请选择园区" label-in-value allowClear @change="farmChange">
                  <a-select-option
                      v-for="(item, index) in farmList"
                      :key="index" :value="item.FarmId">
                    {{item.FarmName}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" >
              <a-form-item label="选择地块" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                <a-select placeholder="请选择地块" label-in-value allowClear @change="houseChange">
                  <a-select-option
                      v-for="(item, index) in greenHouseList"
                      :key="index" :value="item.GreenHouseId">
                    {{item.GreenHouseName}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <div style="margin: 3px 0 0 8px;">
                <a-button type="primary" @click="search">查询</a-button>
                <a-button style="margin-left: 8px" @click="dataInit">重置</a-button>
              </div>
            </a-col>
          </a-row>
        </div>
      </a-form>
    </div>
    <div>
      <a-space class="operator">
        <a-button @click="add" type="primary">新建</a-button>
      </a-space>
      <standard-table style="margin-top: 10px"
                      :loading="loading"
                      :rowKey="(data, index) => index"
                      :columns="columns"
                      :dataSource="configList"
      >
        <div slot="action" slot-scope="{record, index}">
          <a style="margin-right: 8px" @click="editRecord(record, index)">
            <a-icon type="edit"/>编辑
          </a>
          <a-popconfirm title="确定删除?" @confirm="delRecord(record)">
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a href="#" style="margin-right: 8px; color: #f5222d"><a-icon type="delete" />删除</a>
          </a-popconfirm>
          <a-popconfirm title="确定清空该规则告警信息?" @confirm="delAlarmList(record)">
            <a-icon slot="icon" type="question-circle-o" style="color: #faad14" />
            <a href="#" style="color: #faad14"><a-icon type="delete" />清空告警</a>
          </a-popconfirm>
        </div>
      </standard-table>
    </div>
    <!-- 编辑modal -->
    <a-modal
        :title="modalTitle"
        width="900px"
        :visible="visible"
        :confirm-loading="confirmLoading"
        @ok="confirm"
        @cancel="editCancel"
    >
      <a-form-model
          ref="optionsForm"
          :model="data"
          :rules="rules"
          :label-col="{span: 4}"
          :wrapper-col="{span: 14}">
        <a-form-model-item label="园区名称" prop="FarmName">
          <a-select v-model="data.FarmName" placeholder="请选择园区" @change="mdlFarmChange" :disabled="data.Id ? true : false">
            <a-select-option v-for="(item, index) in farmList" :key="index" :value="item.FarmId">
              {{item.FarmName}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="地块名称" prop="GreenHouseName">
          <a-select v-model="data.GreenHouseName" placeholder="请选择地块" @change="mdlHouseChange" :disabled="data.Id ? true : false">
            <a-select-option v-for="(item, index) in greenHouseList" :key="index" :value="item.GreenHouseId">
              {{item.GreenHouseName}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="设备名称" prop="DevName">
          <a-select label-in-value placeholder="请选择设备" @change="devChange">
            <a-select-option v-for="(item, index) in devList" :key="index" :value="item.DevCode">
              {{item.DevName}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="配置名称" prop="AlarmConfigName">
          <a-input v-model="data.AlarmConfigName" type="text" allowClear/>
        </a-form-model-item>
        <a-form-model-item label="设备属性" prop="DisplayName">
          <a-select v-model="data.DisplayName" placeholder="请选择设备属性" @change="propertyChange">
            <a-select-option v-for="(item, index) in kvList" :key="index" :value="item.FieldName">
              {{item.DisplayName}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="比较" prop="CompareType">
          <a-select v-model="data.CompareType" placeholder="请选择设备属性" @change="compareChange">
            <a-select-option v-for="(item, index) in compareType" :key="index" :value="item">
              {{compareName(item)}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="阈值" prop="Value">
          <a-input-number v-model="data.Value"/>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-card>
</template>

<script>
  import { FormModel } from 'ant-design-vue';
  import StandardTable from '@/components/table/StandardTable'
  import { list as farmList } from '@/services/farm'
  import { list as greenHouseList } from '@/services/greenhouse'
  import { list as devList} from '@/services/dev'
  import { configList, configAdd, configEdit, configDel, alarmDelByRule } from '@/services/alarm'
  import {filterArray, trimAll} from '@/utils/util'
  const columns = [
    {
      title: '园区名称',
      dataIndex: 'FarmName',
      scopedSlots: { customRender: 'FarmName' }
    },
    {
      title: '地块名称',
      dataIndex: 'GreenHouseName',
      scopedSlots: { customRender: 'GreenHouseName' }
    },
    {
      title: '规则名称',
      dataIndex: 'AlarmConfigName',
      scopedSlots: { customRender: 'AlarmConfigName' }
    },
    {
      title: '设备名称',
      dataIndex: 'DevName',
      scopedSlots: { customRender: 'DevName' }
    },
    {
      title: '属性名称',
      dataIndex: 'DisplayName',
      scopedSlots: { customRender: 'DisplayName' }
    },
    {
      title: '比较',
      dataIndex: 'CompareName',
      scopedSlots: { customRender: 'CompareName' }
    },
    {
      title: '阈值',
      dataIndex: 'Value',
      scopedSlots: { customRender: 'Value' }
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: '220px',
      scopedSlots: { customRender: 'action' }
    }
  ]
  export default {
    name: "AlarmOptions",
    data() {
      return {
        loading: false,
        visible: false,
        modalTitle: '',
        confirmLoading: false,
        columns,
        farmList: [],
        greenHouseList: [],
        devList: [],
        kvList: [],
        configList: [],
        compareType: ['above', 'equal', 'below', 'notEqual'],
        query: {
          farmId: undefined,
          farmName: undefined,
          greenHouseId: undefined,
          greenHouseName: undefined,
          devId: undefined,
          devName: undefined
        },
        dataIndex: null,
        data: {
          AlarmConfigName: '',
          CompareType: '',
          DevCode: '',
          DevName: '',
          DisplayName: '',
          FarmId: '',
          FieldName: '',
          GreenHouseId: '',
          Id: '',
          Value: ''
        },
        rules: {
          FarmName: [
            { required: true, message: '请选择园区', trigger: 'change' },
          ],
          GreenHouseName: [
            { required: true, message: '请选择地块', trigger: 'change' },
          ],
          DevName: [
            { required: true, message: '请选择设备', trigger: 'change' },
          ],
          DisplayName: [
            { required: true, message: '请选择设备属性', trigger: 'change' },
          ],
          AlarmConfigName: [
            { required: true, message: '请输入配置名称', trigger: 'blur' },
          ],
          CompareType: [
            { required: true, message: '请选择比较方式', trigger: 'change' },
          ],
          Value: [
            { required: true, message: '请输入阈值', trigger: 'blur' },
          ]
        }
      }
    },
    computed: {
      compareName(e) {
        let v = ''
        return e => {
          switch (e) {
            case 'above':
              v = '大于'
              break
            case 'equal':
              v = '等于'
              break
            case 'below':
              v = '小于'
              break
            case 'notEqual':
              v = '不等于'
              break
            default:
              v = '未知'
          }
          return v
        }
      }
    },
    components: {
      StandardTable,
      FormModel
    },
    created() {
      this.getFarmList()
    },
    methods: {
      async getFarmList() {
        let res = await farmList()
        this.farmList = res.Data
      },
      async getGreenHouseList() {
        let res = await greenHouseList(this.query.farmId)
        this.greenHouseList = res.Data
      },
      async search() {
        if(!this.query.greenHouseId) {
          this.$message.error('请选择地块')
          return
        }
        this.loading = true
        let resDev = await devList(this.query.greenHouseId)
        this.devList = resDev.Data
        let res = await configList(this.query.greenHouseId)
        this.configList = res.Data.map(item => {
          let devInfo = this.devList.find(obj => item.DevCode == obj.DevCode)
          let kvInfo = filterArray(devInfo.KvList).find(obj => obj.FieldName == item.FieldName)
          return {
            Id: item.Id,
            AlarmConfigName: item.AlarmConfigName,
            CompareType: item.CompareType,
            CompareName: this.compareName(item.CompareType),
            DevCode: item.DevCode,
            DevName: devInfo.DevName,
            DisplayName: kvInfo.DisplayName,
            FarmId: this.query.farmId,
            FarmName: this.query.farmName,
            FieldName: item.FieldName,
            GreenHouseId: item.GreenHouseId,
            GreenHouseName: this.query.greenHouseName,
            Value: item.Value
          }
        })
        this.loading = false
      },
      editRecord(row, index) {
        this.modalTitle = '编辑规则'
        this.dataIndex = index
        this.data = {...row} //深度复制
        const devInfo = this.devList.find(item => item.DevCode == row.DevCode)
        this.kvList = filterArray(devInfo.KvList)
        this.visible = true
      },
      delRecord(row) {
        console.log(row);
        if(!row.Id) {
          this.$message.error('无效规则')
          return
        }
        configDel(row.Id).then(res => {
          if(res.Code == 0) {
            this.$message.success('删除成功')
            this.search()
          } else this.$message.error('删除失败')
        }).catch(err => {
          console.log(err)
          this.$message.error('删除失败')
        })
      },
      //清空告警信息
      delAlarmList(row) {
        console.log(row);
        alarmDelByRule(row.Id).then(res => {
          if(res.Code == 0) {
            this.$message.success('清空成功')
            this.search()
          } else this.$message.error('清空失败')
        }).catch(err => {
          console.log(err)
          this.$message.error('清空失败')
        })
      },
      farmChange(obj) {
        console.log('园区', obj);
        this.query.farmId = obj.key
        this.query.farmName = obj.label
        this.queryInit()
        this.getGreenHouseList()
      },
      houseChange(obj) {
        console.log('地块', obj);
        this.query.greenHouseId = obj.key
        this.query.greenHouseName = obj.label
      },
      queryInit() {
        this.query.greenHouseId = undefined
        this.query.greenHouseName = undefined
      },
      dataInit() {
        // this.$options可以获取配置对象，配置对象的data函数执行，返回的响应式数据为空的
        Object.assign(this.$data, this.$options.data())
        this.getFarmList()
      },
      add() {
        this.modalTitle = '新增规则'
        this.visible = true
      },
      confirm() {
        this.$refs.optionsForm.validate(valid => {
          if (valid) {
            console.log(this.data);
            this.confirmLoading = true
            if(this.data.Id == '') {
              this.data.Id = 0
              configAdd(this.data).then(res => {
                if(res.Code == 0) {
                  this.$message.success("添加成功")
                  this.data = this.$options.data().data
                } else this.$message.success("添加失败")
              }).catch(err => {
                console.log(err)
                this.$message.error('添加失败')
              })
            } else {
              //修改
              configEdit(this.data).then(res => {
                if(res.Code == 0) {
                  this.$message.success("修改成功")
                  this.search()
                } else {
                  this.$message.error('修改失败')
                }
              }).catch(err => {
                this.$message.error('修改失败')
                console.log(err);
              })
            }
            this.visible = false
            this.confirmLoading = false
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      },
      editCancel() {
        this.visible = false
        this.data = this.$options.data().data
        this.$refs.optionsForm.resetFields();
      },
      mdlFarmChange(e) {
        this.data.FarmId = e
        this.query.farmId = e
        this.data.GreenHouseName = ''
        this.getGreenHouseList()
      },
      async mdlHouseChange(e) {
        this.data.GreenHouseId = e
        this.data.DevName = ''
        let resDev = await devList(this.data.GreenHouseId) //重查设备
        this.devList = resDev.Data
      },
      devChange(obj) {
        this.data.DevCode = obj.key
        this.data.DevName = trimAll(obj.label)
        const devInfo = this.devList.find(item => item.DevCode == obj.key)
        this.kvList = filterArray(devInfo.KvList)
      },
      propertyChange(e) {
        this.data.FieldName = e
      },
      compareChange(e) {
        this.data.CompareType = e
      }
    }
  }
</script>

<style scoped>

</style>
